﻿using StructuredProgrammingAssignment.Models;
using System;
using System.Net.Http;
using System.Web.Http;

namespace StructuredProgrammingAssignment.Controllers
{
	public class SPApiController : ApiController
	{
		private string defaultSuccessMessage = "operation success";
		private string defaultFailureMessage = "operation failed";

		/**
		 * Success result handlers.
		 **/
		protected Object[] SuccessResult(Object obj) {
			return SuccessResult(obj, defaultSuccessMessage);
		}

		protected Object[] SuccessResult(Object obj, string logMessage) {
			string controller = (string)Request.GetRouteData().Values["controller"];
			string action = (string)Request.GetRouteData().Values["action"];
			string path = (string)Request.RequestUri.PathAndQuery;

			SPLog.Info("log", "[Success] " + logMessage, controller, action, path);
			return new Object[] { "success", obj };
		}

		/**
		 * Failure result handlers.
		 **/
		protected Object[] FailureResult(Object obj) {
			return FailureResult(obj, defaultFailureMessage);
		}

		protected Object[] FailureResult(Object obj, string logMessage) {
			string controller = (string)Request.GetRouteData().Values["controller"];
			string action = (string)Request.GetRouteData().Values["action"];
			string path = (string)Request.RequestUri.PathAndQuery;

			SPLog.Error("log", "[Failure] " + logMessage, controller, action, path);
			return new Object[] { "failure", obj };
		}

		/**
		 * Exception handlers.
		 **/
		protected Object[] ExceptionResult(Exception obj) {
			return ExceptionResult(obj, obj.Message);
		}

		protected Object[] ExceptionResult(Exception obj, string logMessage) {
			string controller = (string)Request.GetRouteData().Values["controller"];
			string action = (string)Request.GetRouteData().Values["action"];
			string path = (string)Request.RequestUri.PathAndQuery;

			SPLog.Error("log", "[Exception] " + logMessage, controller, action, path);
			return new Object[] { "exception", obj.Message };
		}

		/**
		 * Log warning.
		 **/
		protected void LogWarning(string logMessage) {
			string controller = (string)Request.GetRouteData().Values["controller"];
			string action = (string)Request.GetRouteData().Values["action"];
			string path = (string)Request.RequestUri.PathAndQuery;

			SPLog.Warn("log", "[Warn] " + logMessage, controller, action, path);
		}
	}
}
